from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QWidget, QLabel, QPushButton, QApplication, QGridLayout,\
    QHBoxLayout, QScrollArea, QStackedWidget, QMessageBox, QVBoxLayout, QInputDialog,\
    QLineEdit, QListView
from PyQt5.QtGui import QPixmap, QCursor
import sys
from qtDesigner.orderItem import Ui_orderItem
from qtDesigner.orderMsgWidget import Ui_orderDetailWidget
from qtDesigner.goodsItems import Ui_GoodsItem
from qtDesigner.groupOrderItem import Ui_GroupOrderItem
import requests
from base64 import b64decode
import copy
from Dialog import WarningMessageBox, QuestionMessageBox
from handler.orderHandle import orderHandle
from shopInterfaceTools import shopItem, ItemDisplayWidget, hClsWidget

from PyQt5.QtCore import QUrl
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest

orderList = [
    {
        "out_trade_no": [
            "202010200630103653003321870671",
            "202010200630103653323321870324",
        ],
        "products": [
            {
                "price" : 0.03,
                "image" : "https://www.yixianshenji.com/img/Banner1.jpg",
                "number" : 5,
                "discount" : 0,
                "goods_title": "白菜",
                'buy_type': 1,
            },
            {
                "price" : 0.03,
                "image" : "https://www.yixianshenji.com/img/Banner1.jpg",
                "number" : 5,
                "discount" : 0,
                "goods_title": "白菜",
                'buy_type': 1,
            },
{
                "price" : 0.03,
                "image" : "https://www.yixianshenji.com/img/Banner1.jpg",
                "number" : 5,
                "discount" : 0,
                "goods_title": "白菜",
                'buy_type': 1,
            },
            {
                "price" : 0.03,
                "image" : "https://www.yixianshenji.com/img/Banner1.jpg",
                "number" : 5,
                "discount" : 0,
                "goods_title": "白菜",
                'buy_type': 1,
            },
            {
                "price": 0.03,
                "image": "https://www.yixianshenji.com/img/Banner1.jpg",
                "number": 5,
                "discount": 0,
                "goods_title": "白菜",
                'buy_type': 1,
            }
        ],
        "total_fee" : 0.05,
        "total_count" : 2,
        "total_discount_fee" : 0.05,
        "user" : "6d45416c7a64304673705278",
        "status" : 0,
        'order_type': 1,
        "create_at" : "2020-10-20T 06:30:10",
        "mobile" : "18682409503",
        "address": {
            "name" : "邓磊磊",
            "addressName": "创锦1号A座(创业二路125号创锦1号",
            "address": "广东省深圳市宝安区创业二路127号",
        },
        "delivery_info" : [
                {
                    "name": "天天快递",
                    "no": "46464sdfdsfsa6464165416"
                }
            ]
    },
    {
            "out_trade_no": [
                "202010200630103653003321870672",
            ],
            "products": [
                {
                    "title" : "全民采摘园",
                    "image" : "https://www.yixianshenji.com/img/Banner1.jpg",
                    "id" : 8,
                    "items" : "白菜",
                    "price" : 0.02,
                    "count" : "2",
                    'buy_type': 2,
                },
                {
                    "title" : "全民采摘园",
                    "image" : "https://www.yixianshenji.com/img/Banner1.jpg",
                    "id" : 8,
                    "items" : "白菜",
                    "price" : 0.02,
                    "count" : "2",
                    'buy_type': 2,
                }
            ],
            "total_fee": 0.05,
            "total_count": 2,
            "total_discount_fee": 0.05,
            "user": "6d45416c7a64304673705278",
            "status": 0,
            'order_type': 4,
            "create_at": "2020-10-20T 06:30:10",
            "mobile" : "18682409503",
            "address": {
                "name" : "邓磊磊",
                "addressName": "创锦1号A座(创业二路125号创锦1号)",
                "address": "广东省深圳市宝安区创业二路127号",
            },
            "delivery_info" : [
                    {
                        "name": "天天快递",
                        "no": "46464sdfdsfsa6464165416"
                    }
                ]
        },
        {
            "out_trade_no": [
                "202010200630103653003321870672",
            ],
            "products": [
                {
                    "title" : "菜园",
                    "items" : "白菜",
                    "image" : "https://www.yixianshenji.com/img/Banner1.jpg",
                    "id" : 8,
                    "price" : 0.02,
                    "count" : "2",
                    'buy_type': 2,
                },
            ],
            "total_fee": 0.05,
            "total_count": 2,
            "total_discount_fee": 0.05,
            "user": "6d45416c7a64304673705278",
            "status": 0,
            'order_type': 4,
            "create_at": "2020-10-20T 06:30:10",
            "mobile" : "18682409503",
            "address": {
                "name" : "邓磊磊",
                "addressName": "创锦1号A座(创业二路125号创锦1号)",
                "address": "广东省深圳市宝安区创业二路127号",
            },
            "delivery_info" : [
                    {
                        "name": "天天快递",
                        "no": "46464sdfdsfsa6464165416"
                    }
                ]
        },
]

groupData = [
    {
        "number": 3,  # 已拼团人数
        "goods_title": "鱼",
        "image": "https://www.yixianshenji.com/img/Banner1.jpg"
    },
    {
        "number": 4,  # 已拼团人数
        "goods_title": "鸡肉",
        "image": "https://www.yixianshenji.com/img/Banner1.jpg"
    }
]

class orderBtn(QPushButton):
    selected = pyqtSignal(str)

    def __init__(self, classname, parent=None):
        super(orderBtn, self).__init__(parent=parent)
        self.setText(classname)
        self.setObjectName("orderBtn")
        self.setAttribute(Qt.WA_StyledBackground, True)
        self.clicked.connect(self._emitIndex)
        self.setFixedSize(30, 30)
        self.setCheckable(True)
        self.setAutoExclusive(True)

    def _emitIndex(self):
        self.selected.emit(self.text())

class orderType(QWidget):
    orderTypeChange = pyqtSignal(int)

    def __init__(self, parent=None):
        super(orderType, self).__init__(parent=parent)
        self._titleLb = QLabel()
        self._titleLb.setText("订单")
        self._titleLb.setObjectName("orderTitle")
        self._orderTypeBtnList = list()
        self._goodsStatusMap = dict()
        self._mainLayout = QGridLayout()
        temp = ["全部订单", "普通订单", "团购订单", "合种租地", "活动订单"]
        for index in range(5):
            self._orderTypeBtnList.append(orderBtn(temp[index]))
            self._orderTypeBtnList[index].selected.connect(self._onOrderTypeChange)
        self._orderTypeBtnList[0].setChecked(True)
        # 支持qss样式表设置
        self.setAttribute(Qt.WA_StyledBackground, True)

        self.setObjectName("orderType")
        self._initGoodsStatusMap()
        self._initLayout()

    def _initGoodsStatusMap(self):
        self._goodsStatusMap["普通订单"] = 1
        self._goodsStatusMap["团购订单"] = 2
        self._goodsStatusMap["分销订单"] = 3
        self._goodsStatusMap["合种租地"] = 4
        self._goodsStatusMap["活动订单"] = 5
        self._goodsStatusMap["全部订单"] = 100

    def _initLayout(self):
        self._mainLayout.addWidget(self._titleLb, 0, 0, Qt.AlignCenter)
        for each in range(self._orderTypeBtnList.__len__()):
            self._mainLayout.addWidget(self._orderTypeBtnList[each],each+1, 0, Qt.AlignCenter)
        self.setLayout(self._mainLayout)

    def _onOrderTypeChange(self, order_type):
        self.orderTypeChange.emit(self._goodsStatusMap[order_type])

class orderItem(Ui_orderItem, QWidget):
    shopItemClicked = pyqtSignal(dict)

    def __init__(self, parent=None):
        super(orderItem, self).__init__(parent=parent)
        self.setupUi(self)
        self._data = None
        self._dataIndex = None
        self._orderTypeMap = dict()
        self._goodsStatusMap = dict()
        self._initOrderTypeMap()
        self._initGoodsStatusMap()
        self.setFixedSize(643, 165)
        self.setObjectName("myOrderItem")
        self.setAttribute(Qt.WA_StyledBackground, True)

    # 1商城订单（正常），2商城订单（团购）3分销订单，4合种租地, 5是活动
    def _initOrderTypeMap(self):
        self._orderTypeMap[1] = "普通订单"
        self._orderTypeMap[2] = "团购订单"
        self._orderTypeMap[3] = "分销订单"
        self._orderTypeMap[4] = "合种租地"
        self._orderTypeMap[5] = "活动订单"
        self._orderTypeMap[100] = "全部订单"

    def _initGoodsStatusMap(self):
        self._goodsStatusMap[0] = "待付款"
        self._goodsStatusMap[1] = "拼单中"
        self._goodsStatusMap[2] = "待发货"
        self._goodsStatusMap[3] = "已完成"
        self._goodsStatusMap[4] = "确认退款"
        self._goodsStatusMap[5] = "已退款"
        self._goodsStatusMap[6] = "拼单失败"
        self._goodsStatusMap[8] = "待收货"
        self._goodsStatusMap[9] = "订单已关闭"
        self._goodsStatusMap[11] = "取消"
        self._goodsStatusMap[13] = "已收货"
        self._goodsStatusMap[1000] = "刷新订单"
        self._goodsStatusMap[100] = "全部"

    def getDictData(self, data, key):
        return data.get(key) if (data.get(key) is not None) else ""

    def updateData(self, data):
        self._data = data
        try:
            order_type = self.getDictData(data, "order_type")
            if order_type != "":
                self.topTitle.setText(self._orderTypeMap[order_type])
            else:
                self.topTitle.setText(order_type)
            self.weChartNameEdit.setText(self.getDictData(data["address"], "name"))
            self.priceEdit.setText("¥ " + str(self.getDictData(data, "real_payment")))
            self.numberEdit.setText(str(int(self.getDictData(data, "total_count"))))
            self.phone.setText(self.getDictData(data, "mobile"))
            self.statusEdit.setText(self._goodsStatusMap[data["status"]])
        except Exception as e:
            print(e)

    def setDataIndex(self, index):
        self._dataIndex = index

    def getData(self):
        return self._data

    def dataIndex(self):
        return self._dataIndex

    def mouseReleaseEvent(self, event):
        super(orderItem, self).mouseReleaseEvent(event)
        self.shopItemClicked.emit(self._data)

    def getSize(self):
        return [645, 165]

class orderMainDetailMsgWidget(Ui_orderDetailWidget, QWidget):
    cancelBtnClicked = pyqtSignal()

    def __init__(self, parent=None):
        super(orderMainDetailMsgWidget, self).__init__(parent=parent)
        self._data = None
        self._handle = orderHandle()
        self._currentEditItem = None
        self._goodsStatusMap = dict()
        self._confirmBtnTextMap = dict()
        self._cancelBtnTextMap = dict()

        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setupUi(self)
        self.expressNumberEdit.setPlaceholderText("请输入快递单号:")
        self.confirmButton.clicked.connect(self._onSubmit)
        self.cancelBtn.clicked.connect(self._onCancel)
        self.backButton.clicked.connect(self._onBack)
        self._initGoodsStatusMap()
        self._initConfirmBtnTextMap()
        self._initCancelBtnTextMap()
        self.addressEdit.setReadOnly(True)
        self.expCompany.addItems(["", "天天快递", "圆通速递", "申通快递"
                                  , "中通快递", "百世快递", "韵达快递",
                                  "顺丰速运", "京东物流", "EMS", "邮政快递包裹",
                                  "众邮快递", "德邦快递", "宅急送", "极兔快递",
                                  "邮政标准快递", "优速快递", "苏宁物流"])
        self.expCompany.setView(QListView())
        self.expCompany.view().setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.expCompany.setCurrentIndex(0)
        self.setFixedSize(1189, 389)

    def _onSubmit(self):
        order_operation = self.confirmButton.text()

        # 处理订单
        if order_operation == "确认发货":
            if self._data["order_type"] == 5:
                WarningMessageBox("活动订单不能发货").exec()

            elif self._data["order_type"] == 4:
                ret = QuestionMessageBox("请确认发放").exec()
                if ret == QMessageBox.Yes:
                    order_no = self.orderNumberEdit.text()
                    state, ret = self._handle.goods_deliver(order_no, "", "")
                    print(ret)
                    if not state:
                        WarningMessageBox("发放失败，服务器异常").exec()
                        return
                    self.expressNumberEdit.setReadOnly(True)
                    self.goodsStatusEdit.setText("待收货")
                    self._data["status"] = 8
                    self.confirmButton.setText(self._confirmBtnTextMap[self._data["status"]])
                    self.cancelBtn.setText("取消订单")

            else:
                if self.expressNumberEdit.text() == "" or self.expCompany.currentText() == "":
                    WarningMessageBox("快递单号和快递公司不能为空").exec()
                else:
                    ret = QuestionMessageBox("请确认快递单号" + "\n" + self.expCompany.currentText() + ":" +
                                             self.expressNumberEdit.text()).exec()
                    if ret == QMessageBox.Yes:
                        order_no = self.orderNumberEdit.text()
                        express_company = self.expCompany.currentText()
                        express_number = self.expressNumberEdit.text()
                        state, ret = self._handle.goods_deliver(order_no, express_company, express_number)
                        print(ret)
                        if not state:
                            WarningMessageBox("发货失败，服务器异常").exec()
                            return
                        self.expressNumberEdit.setReadOnly(True)
                        self.goodsStatusEdit.setText("待收货")
                        self._data["status"] = 8
                        self._data["out_trade_no"] = [
                                                        {
                                                            "name": express_company,
                                                            "no": express_number
                                                        },
                                                    ]
                        self.confirmButton.setText(self._confirmBtnTextMap[self._data["status"]])
                        self.cancelBtn.setText(self._cancelBtnTextMap[self._data["status"]])

        elif order_operation == "确认退款":
            self._changeOrderStatus("请确认退款", 5, "服务器异常")

        elif order_operation == "修改邮费":
            order_no = self.orderNumberEdit.text()
            orders = order_no.split(",")
            order_count = orders.__len__()
            new_fee = 0
            ret = QuestionMessageBox("共" + str(order_count) + "个订单\n请依次设置邮费").exec()
            if ret == QMessageBox.Yes:
                for each in range(order_count):
                    fee, ok = QInputDialog.getDouble(self, "订单" + str(each) + "邮费",
                                                     "请输入修改的邮费:", 0, 0, 10000, 2)
                    if ok:
                        status, ret = self._handle.alter_delivery_fee(orders[each], fee)
                        print(ret)
                        new_fee += fee
                        if not status:
                            WarningMessageBox("邮费修改失败,服务器异常").exec()
                            return
                self.freightEdit.setText(str(new_fee))
                self._data["status"] = 1000
                self.goodsStatusEdit.setText(self._goodsStatusMap[self._data["status"]])
                self.confirmButton.setText(self._confirmBtnTextMap[self._data["status"]])
                self.cancelBtn.setText(self._cancelBtnTextMap[self._data["status"]])

        elif order_operation == "请刷新订单":
            WarningMessageBox("请点击刷新订单").exec()

        else:
            WarningMessageBox("无效操作").exec()

    def _changeOrderStatus(self, ques_msg, order_status, warning_msg, order_type="", goods_id=0):
        ret = QuestionMessageBox(ques_msg).exec()

        if ret == QMessageBox.Yes:
            order_no = self.orderNumberEdit.text()
            status, ret = self._handle.change_order_status(order_no, order_status, order_type, goods_id)
            print(ret)

            if not status:
                WarningMessageBox(warning_msg).exec()
                return
            self._data["status"] = order_status
            self.goodsStatusEdit.setText(self._goodsStatusMap[self._data["status"]])
            self.confirmButton.setText(self._confirmBtnTextMap[self._data["status"]])
            self.cancelBtn.setText(self._cancelBtnTextMap[self._data["status"]])

    def _onCancel(self):
        order_operation = self.cancelBtn.text()

        # 处理订单
        if order_operation == "拒绝退款":
            self._changeOrderStatus("请确认拒绝退款", 2, "服务器异常")

        elif order_operation == "取消订单":
            if self._data["order_type"] == 5:
                self._changeOrderStatus("请确认取消订单", 9, "服务器异常", "activity", self._data["products"][0]["id"])
            elif self._data["order_type"] == 4:
                self._changeOrderStatus("请确认取消订单", 9, "服务器异常", "land",
                                        self._data["products"][0]['landPlantItems'][0]['item_id'])
            else:
                self._changeOrderStatus("请确认取消订单", 4, "服务器异常")

        elif order_operation == "请刷新订单":
            WarningMessageBox("请点击刷新").exec()

        else:
            WarningMessageBox("无效操作").exec()

    def _onBack(self):
        self.cancelBtnClicked.emit()

    def _initGoodsStatusMap(self):
        self._goodsStatusMap[0] = "待付款"
        self._goodsStatusMap[1] = "拼单中"
        self._goodsStatusMap[2] = "待发货"
        self._goodsStatusMap[3] = "已完成"
        self._goodsStatusMap[4] = "确认退款"
        self._goodsStatusMap[5] = "已退款"
        self._goodsStatusMap[6] = "拼单失败"
        self._goodsStatusMap[8] = "待收货"
        self._goodsStatusMap[9] = "订单已关闭"
        self._goodsStatusMap[11] = "取消"
        self._goodsStatusMap[13] = "已收货"
        self._goodsStatusMap[1000] = "刷新订单"
        self._goodsStatusMap[100] = "全部"

    def _initConfirmBtnTextMap(self):
        self._confirmBtnTextMap[0] = "修改邮费"
        self._confirmBtnTextMap[1] = "无操作"
        self._confirmBtnTextMap[2] = "确认发货"
        self._confirmBtnTextMap[3] = "无操作"
        self._confirmBtnTextMap[4] = "确认退款"
        self._confirmBtnTextMap[5] = "无操作"
        self._confirmBtnTextMap[6] = "无操作"
        self._confirmBtnTextMap[8] = "无操作"
        self._confirmBtnTextMap[9] = "无操作"
        self._confirmBtnTextMap[11] = "无操作"
        self._confirmBtnTextMap[13] = "无操作"
        self._confirmBtnTextMap[1000] = "请刷新订单"
        self._confirmBtnTextMap[4098] = "无操作"

    def _initCancelBtnTextMap(self):
        self._cancelBtnTextMap[0] = "无操作"
        self._cancelBtnTextMap[1] = "无操作"
        self._cancelBtnTextMap[2] = "取消订单"
        self._cancelBtnTextMap[3] = "无操作"
        self._cancelBtnTextMap[4] = "拒绝退款"
        self._cancelBtnTextMap[5] = "无操作"
        self._cancelBtnTextMap[6] = "无操作"
        self._cancelBtnTextMap[8] = "无操作"
        self._cancelBtnTextMap[9] = "无操作"
        self._cancelBtnTextMap[11] = "无操作"
        self._cancelBtnTextMap[13] = "无操作"
        self._cancelBtnTextMap[1000] = "请刷新订单"
        self._cancelBtnTextMap[4098] = "无操作"

    def getDictData(self, data, key):
        return data.get(key) if (data.get(key) is not None) else ""

    def updateData(self, data):
        self._data = data
        try:
            #self._currentEditItem = self.sender()
            if self._data["order_type"] == 4 and self._data["status"] == 8:
                self.cancelBtn.setText("取消订单")
            elif self._data["order_type"] == 4 and self._data["status"] == 13:
                self.cancelBtn.setText("取消订单")
            else:
                self.cancelBtn.setText(self._cancelBtnTextMap[data["status"]])
            self.confirmButton.setText(self._confirmBtnTextMap[data["status"]])
            self.RealName.setText(self.getDictData(data["address"], "name"))
            self.priceEdit.setText(str(self.getDictData(data, "real_payment")))
            self.numberEdit.setText(str(int(self.getDictData(data, "total_count"))))
            self.freightEdit.setText(str(self.getDictData(data, "delivery_fee")))
            self.phoneEdit.setText(self.getDictData(data, "mobile"))
            self.addressEdit.setPlainText(self.getDictData(data["address"], "address"))
            self.addressName.setText(self.getDictData(data["address"], "addressName"))
            self.orderNumberEdit.setText(",".join(data["out_trade_no"]))
            # self.freightEdit.setText(str(self.getDictData(data, "express_price")))   # 运费

            if data["delivery_info"].__len__() > 0:
                self.expressNumberEdit.setText(data["delivery_info"][0]["no"])
                index = self.expCompany.findText(data["delivery_info"][0]["name"])
                self.expCompany.setCurrentIndex(index if(index != -1) else 0)
            else:
                self.expressNumberEdit.setText("")
                self.expCompany.setCurrentIndex(0)

            self.goodsStatusEdit.setText(self._goodsStatusMap[data["status"]])

            if data["status"] != 2:
                self.expressNumberEdit.setReadOnly(True)
            else:
                self.expressNumberEdit.setReadOnly(False)
        except Exception as e:
            print(e)

    def currentEditItem(self):
        return self._currentEditItem

    def getData(self):
        return self._data

class goodsItem(Ui_GoodsItem, QWidget):
    def __init__(self, parent=None):
        super(goodsItem, self).__init__(parent=parent)
        self.setupUi(self)
        self.setFixedSize(761, 191)
        self.m_netAccessManager = QNetworkAccessManager(self)
        self.m_netReply = None

    def q_request(self, url):
        if url.startswith("http"):
            if self.m_netReply is not None:
                self.m_netReply.disconnect()

            req = QNetworkRequest(QUrl(url))
            self.m_netReply = self.m_netAccessManager.get(req)

            self.m_netReply.finished.connect(self.readData)

        else:
            self._displayimg(url, self.pictureLb)

    def readData(self):
        recvData = self.m_netReply.readAll()
        pix = QPixmap()
        pix.loadFromData(recvData)
        pix = pix.scaled(self.pictureLb.width(), self.pictureLb.height())
        self.pictureLb.setPixmap(pix)

    def getDictData(self, data, key):
        return data.get(key) if (data.get(key) is not None) else ""

    def updateData(self, data):
        if int(data['buy_type']) == 1:
            self.goods_name.setText(self.getDictData(data, "goods_title"))
            self.goods_price.setText(str(self.getDictData(data, "price")))
            self.goods_number.setText(str(self.getDictData(data, "number")))
            #self._displayImg(data["image"], self.pictureLb)
            self.q_request(data["image"])
            self.setGoodsMode(self.getDictData(data, "buy_type"))
        elif int(data['buy_type']) == 2:
            self.land_name.setText(self.getDictData(data, "title"))
            self.plant_name.setText(self.getDictData(data, "items"))
            self.plant_price.setText(str(self.getDictData(data, "price")))
            #self._displayImg(data["image"], self.pictureLb)
            self.q_request(data["image"])
            self.setGoodsMode(self.getDictData(data, "buy_type"))
        elif int(data['buy_type']) == 3:
            self.activity_name.setText(self.getDictData(data, "title"))
            self.activity_price.setText(str(self.getDictData(data, "price")))
            self.join_number.setText(str(self.getDictData(data, "count")))
            #self._displayImg(data["image"], self.pictureLb)
            self.q_request(data["image"])
            self.setGoodsMode(self.getDictData(data, "buy_type"))

    def setGoodsMode(self, buy_type):
        # 显示商品
        if buy_type is not None:
            buy_type = int(buy_type)
        if buy_type == 1:
            self.LandMsgLb.hide()
            self.activityWidget.hide()
            self.GoodsMsgLb.show()

        # 显示租地产品
        elif buy_type == 2:
            self.GoodsMsgLb.hide()
            self.activityWidget.hide()
            self.LandMsgLb.show()

        # 显示活动
        elif buy_type == 3:
            self.LandMsgLb.hide()
            self.GoodsMsgLb.hide()
            self.activityWidget.show()

    def _displayImg(self, url, label):
        pix = QPixmap()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        if url is None:
            pass
        elif url.startswith("http"):
            QApplication.processEvents()
            response = requests.get(url)
            pix.loadFromData(response.content)
            pix = pix.scaled(label.width(), label.height())
            label.setPixmap(pix)
        elif url == "请点击插入图片":
            label.setText(url)
        else:
            url = url.encode("utf-8")
            image_data = b64decode(url)
            pix.loadFromData(image_data)
            pix = pix.scaled(label.width(), label.height())
            label.setPixmap(pix)

        QApplication.restoreOverrideCursor()

    def getSize(self):
        return [761, 191]


class orderItemMsgWidget(QWidget):
    cancelBtnClicked = pyqtSignal()
    goodsStatus = pyqtSignal(list)
    goodsDelete = pyqtSignal(list)

    def __init__(self, parent=None):
        super(orderItemMsgWidget, self).__init__(parent=parent)
        self._data = None
        self._currentEditItem = None
        self.mainMsgWidget = orderMainDetailMsgWidget()
        self.goodsItems = ItemDisplayWidget(item=goodsItem, data=[], init_data=[],
                                            col_count=2, has_edit=False, has_add_btn=False)
        self.mainLayout = QVBoxLayout()

        self.mainMsgWidget.cancelBtnClicked.connect(self._onBack)
        # 布局
        self.mainLayout.addWidget(self.mainMsgWidget)
        self.mainLayout.addWidget(self.goodsItems)
        self.setLayout(self.mainLayout)

    def _onBack(self):
        self.cancelBtnClicked.emit()

    def updateData(self, data):
        self._data = data
        self._currentEditItem = self.sender()
        self.goodsItems.disPlayGoodsItem(data["products"], refresh=True, data_refresh=True)
        self.mainMsgWidget.updateData(data)

    def currentEditItem(self):
        return self._currentEditItem

    def getEditedData(self):
        return self._data

class orderItemDisPlayWidget(ItemDisplayWidget):
    def __init__(self, parent=None):
        super(orderItemDisPlayWidget, self).__init__(parent=parent, item=orderItem, data=[], init_data=[],
                                                     col_count=2, edit_widget=orderItemMsgWidget, has_add_btn=False,
                                                     on_cancel_refresh_data=True)

        self._goodsStatusMap = dict()
        self._current_type = 100
        self._current_status = 100
        self._initGoodsStatusMap()

    def order_fliter(self, order_type=None, status=None):
        if order_type is None:
            order_type = self._current_type
            status = self._goodsStatusMap[status]
        elif status is None:
            status = self._current_status

        display_order_list = list()
        if order_type == 100 and status == 100:
            self._current_status = status
            self._current_type = order_type
            for each in self._data:
                status = each.get("status")
                if status is not None and status != 5 and status != 13 and status != 3:
                    display_order_list.append(each)
            self.disPlayGoodsItem(display_order_list, refresh=True)

        elif order_type != 100 and status == 100:
            for each in self._data:
                ordertype = each.get("order_type")
                if ordertype is not None and ordertype == order_type:
                    display_order_list.append(each)
            self._current_status = status
            self._current_type = order_type
            self.disPlayGoodsItem(display_order_list, refresh=True)

        elif order_type == 100 and status != 100:
            for each in self._data:
                st = each.get("status")
                if st is not None and st == status:
                    display_order_list.append(each)
            self._current_status = status
            self._current_type = order_type
            self.disPlayGoodsItem(display_order_list, refresh=True)

        else:
            for each in self._data:
                st = each.get("status")
                ordertype = each.get("order_type")
                if st is not None and st == status and orderType is not None and ordertype == order_type:
                    display_order_list.append(each)
            self._current_status = status
            self._current_type = order_type
            self.disPlayGoodsItem(display_order_list, refresh=True)

    def _initGoodsStatusMap(self):
        self._goodsStatusMap["待付款"] = 0
        self._goodsStatusMap["拼单中"] = 1
        self._goodsStatusMap["待发货"] = 2
        self._goodsStatusMap["已完成"] = 3
        self._goodsStatusMap["确认退款"] = 4
        self._goodsStatusMap["已退款"] = 5
        self._goodsStatusMap["拼单失败"] = 6
        self._goodsStatusMap["待收货"] = 8
        self._goodsStatusMap["订单已关闭"] = 9
        self._goodsStatusMap["取消"] = 11
        self._goodsStatusMap["已收货"] = 13
        self._goodsStatusMap["全部"] = 100

class groupOrderItem(Ui_GroupOrderItem, QWidget):
    def __init__(self, parent=None):
        super(groupOrderItem, self).__init__(parent=parent)
        self._data = None
        self._handle = orderHandle()
        self.setupUi(self)
        self.setFixedSize(530, 251)
        self.confirmButton.clicked.connect(self._onSuccessToGroup)
        self.groupFailBtn.clicked.connect(self._onFailToGroup)

        self.m_netAccessManager = QNetworkAccessManager(self)
        self.m_netReply = None

    def q_request(self, url):
        if self.m_netReply is not None:
            self.m_netReply.disconnect()

        req = QNetworkRequest(QUrl(url))
        self.m_netReply = self.m_netAccessManager.get(req)

        self.m_netReply.finished.connect(self.readData)

    def readData(self):
        recvData = self.m_netReply.readAll()
        pix = QPixmap()
        pix.loadFromData(recvData)
        pix = pix.scaled(self.pictureLb.width(), self.pictureLb.height())
        self.pictureLb.setPixmap(pix)

    def updateData(self, data):
        self._data = data
        self.groupGoodsName.setText(data["goods_title"])
        self.GroupSize.setText(str(data["number"]))
        #self._displayImg(data["image"], self.pictureLb)
        self.q_request(data["image"])

    def _displayImg(self, url, label):
        pix = QPixmap()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        if url is None:
            pass
        elif url.startswith("http"):
            QApplication.processEvents()
            response = requests.get(url)
            pix.loadFromData(response.content)
            pix = pix.scaled(label.width(), label.height())
            label.setPixmap(pix)
        elif url == "请点击插入图片":
            label.setText(url)
        else:
            url = url.encode("utf-8")
            image_data = b64decode(url)
            pix.loadFromData(image_data)
            pix = pix.scaled(label.width(), label.height())
            label.setPixmap(pix)

        QApplication.restoreOverrideCursor()

    def _changGroupOrderStatus(self, question_msg, order_status, waring_msg="服务器异常"):
        ret = QuestionMessageBox(question_msg).exec()

        if ret == QMessageBox.Yes:
            order_no = ",".join(self._data["out_trade_no"])
            status, ret = self._handle.change_order_status(order_no, order_status)
            print(status)
            print(ret)

            if not status:
                WarningMessageBox(waring_msg).exec()
                return False

            return True

        return False

    # 拼单成功
    def _onSuccessToGroup(self):
        if self.confirmButton.text() == "拼团成功":
            if self._changGroupOrderStatus("请确认成团", 2):
                self.confirmButton.setText("已成团")
                self.groupFailBtn.setText("已成团")
        elif self.confirmButton.text() == "已成团":
            WarningMessageBox("订单已成团").exec()
        else:
            WarningMessageBox("订单已取消成团").exec()

    # 取消拼单
    def _onFailToGroup(self):
        if self.groupFailBtn.text() == "取消拼团":
            if self._changGroupOrderStatus("请确认取消成团", 4):
                self.groupFailBtn.setText("已取消")
                self.confirmButton.setText("已取消")
        elif self.groupFailBtn.text() == "已成团":
            WarningMessageBox("订单已成团").exec()
        else:
            WarningMessageBox("订单已取消成团").exec()

    def getSize(self):
        return [530, 251]

class orderStackWidget(QStackedWidget):
    def __init__(self, parent=None):
        super(orderStackWidget, self).__init__(parent=parent)
        self.normalGoodsItems = orderItemDisPlayWidget()
        self.groupItems = ItemDisplayWidget(item=groupOrderItem, data=[], init_data=[],
                                            col_count=2, has_edit=False, has_add_btn=False)
        self.addWidget(self.normalGoodsItems)
        self.addWidget(self.groupItems)

    def setIndex(self, index):
        self.setCurrentIndex(index)

class orderWidget(QWidget):
    def __init__(self, parent=None):
        super(orderWidget, self).__init__(parent=parent)
        self._handle = orderHandle()
        self._vLayout = QVBoxLayout()
        self._hLayout = QHBoxLayout()
        self._tempWidget = QWidget()
        self._typeContents = orderType()
        self._typeContents.orderTypeChange.connect(self._onTypeChange)
        self._orderStackWidget = orderStackWidget()
        self._statusWidget = hClsWidget(default_cls=["全部", "待付款", "待发货", "待收货",
                                                     "拼单中", "拼单管理", "确认退款", "已收货", "已退款", "刷新"])
        self._statusWidget.addRmDisable()
        self._statusWidget.rowSelected.connect(self._onChangeStatus)
        self._initLayout()

    def _initLayout(self):
        self._vLayout.addWidget(self._statusWidget)
        self._vLayout.addWidget(self._orderStackWidget)
        self._tempWidget.setLayout(self._vLayout)
        self._hLayout.addWidget(self._typeContents, 0, Qt.AlignTop | Qt.AlignLeft)
        self._hLayout.addWidget(self._tempWidget)
        self.setLayout(self._hLayout)

    def _transform_status(self, data):
        for each in data:
            buy_type = each.get("buy_type")
            group_type = each.get("group_type")
            if buy_type is None or group_type is None:
                del data[data.index(each)]
            else:
                if buy_type == 1:
                    if group_type == 1:
                        each["order_type"] = 1
                    elif group_type == 2:
                        each["order_type"] = 2
                    elif group_type == 3:
                        each["order_type"] = 3
                elif buy_type == 2:
                    each["order_type"] = 4
                elif buy_type == 3:
                    each["order_type"] = 5

    def updateGoodsOrderData(self, data):
        self._transform_status(data)
        self._orderStackWidget.normalGoodsItems.setData(data)
        #self._orderStackWidget.normalGoodsItems.disPlayGoodsItem(data, refresh=True, data_refresh=True)
        self._orderStackWidget.normalGoodsItems.order_fliter(status="全部")

    def updateGroupOrderData(self, data):
        self._orderStackWidget.groupItems.disPlayGoodsItem(data, refresh=True, data_refresh=True)

    def _onTypeChange(self, order_type):
        self._orderStackWidget.normalGoodsItems.order_fliter(order_type=order_type)

    def _onChangeStatus(self, text):
        if text == "拼单管理":
            self._orderStackWidget.setCurrentIndex(1)
            state, group = self._handle.get_group_number_data()
            if state:
                self.updateGroupOrderData(group["group_order_count"])
            else:
                WarningMessageBox("数据获取失败，服务器异常").exec()

        elif text == "刷新":
            if self._orderStackWidget.normalGoodsItems.currentIndex() == 1:
                self._orderStackWidget.normalGoodsItems.back(data_refresh=True)

            state, order = self._handle.get_goods_order()

            if state:
                self.updateGoodsOrderData(order["goods_order_list"])
            else:
                WarningMessageBox("数据获取失败，服务器异常").exec()

        else:
            if self._orderStackWidget.normalGoodsItems.currentIndex() == 1:
                self._orderStackWidget.normalGoodsItems.back(data_refresh=True)
            self._orderStackWidget.setCurrentIndex(0)
            self._orderStackWidget.normalGoodsItems.order_fliter(status=text)


def main():
    app = QApplication(sys.argv)
    with open("shopPjt.qss", "r") as f:
        style = f.read()
    app.setStyleSheet(style)
    # ui = orderItemDisPlayWidget()
    # ui.showMaximized()

    # ui = ItemDisplayWidget(item=goodsItem, data=testOrder, init_data=testOrder,
    #                        col_count=1, has_edit=False, has_add_btn=False)

    # ui = orderMainDetailMsgWidget()
    # ui.updateData(orderList[0])

    # ui = orderItemMsgWidget()
    # ui.updateData(orderList[0])

    #ui = orderItemDisPlayWidget()
    h = orderHandle()
    status, order = h.get_goods_order()
    status1, group = h.get_group_number_data()
    ui = orderWidget()
    ui.updateGoodsOrderData(order["goods_order_list"])
    #ui.updateGoodsOrderData(orderList)
    ui.updateGroupOrderData(group["group_order_count"])
    #ui = goodsItem()
    #ui.updateData(testOrder[0])

    #ui = orderItem()
    #ui.updateData(orderList[0])
    ui.show()

    sys.exit(app.exec())

if __name__ == "__main__":
    main()
